Authenticated Requests

  • The URLSession is exactly the same as the foundation API one, but it has been modified to act on a specific User object instead and to automatically manage OAuth related session lifetimes and renewals.

    If you want to make requests that contain the internal user access tokens, you should create a session object with one of the provided extension initializers. Following this, you may use the URLSession as you would any other session, the only difference is that all requests send with this session will contain a Authorization header with a bearer access token inside it.

    Automatic refreshing

    The URLSession sets a custom URLProtocol object internally that is used to managed all requests created with this session. Before forwarding the results of a request back to you, the protocol implementation checks to make sure that the HTTP status code was NOT a 401. If it ever received a 401, it tries to refresh the user tokens internally. It does this by either pausing or stopping all other requests in flight or in queue, and then either resuming them all after a successful refresh of the tokens, or cancelling them all otherwise.

    Note

    Your servers MUST validate the accesstoken that is issued with your requets with the token introspection endpoint.

    Errors

    1. ClientError.userRefreshFailed
    2. ClientError.invalidUser

    If there’s a refresh failure, then the User object that is associated with this URLSession object is logged out, as there is no way to recover short of logging the user back in again.

    See more

    Declaration

    Swift

    class URLSession : NSObject